<?php
/**
 * @orm tablename newsletter_send
 */
class NewsletterSend extends DomArObject {
	
	/**
	 * @orm has child Newsletter inverse sends
	 */
	public $newsletter;
	/**
	 * @orm has child NewsletterList inverse sends
	 */
	public $list;
	/**
	 * @orm bool
	 */
	public $confirmed = false;
	/**
	 * @orm plugin DomArDateTime()
	 */
	public $startTime;
	/**
	 * @orm int(11)
	 */
	public $max = 0;
	/**
	 * @orm int(11)
	 */
	public $sent = 0;
	/**
	 * @orm int(11)
	 */
	public $errors = 0;
	/**
	 * @orm array
	 */
	public $erroredEmails = array();
	/**
	 * @orm longtext
	 */
	public $comment;
	
	const SEND_MAILS_LIMIT = 1;


	public function sendNext() {
		
		if( $this->confirmed == false ) {
			return false;
		}
		
		if( $this->max == 0 ) {
			$this->max = $this->list->emails->count();
			$this->save();
		}
		
		if( $this->max <= $this->sent+$this->errors ) {
			return true;
		}
		
		$mail = $this->newsletter->getPreparedMail();
		
		foreach( $this->list->emails->query()->where('t.active=1')->orderBy('t.id')->limit($this->sent.','.self::SEND_MAILS_LIMIT)->commit() as $email ) {
			
			$mail->addAddress( $email->email, $email->name );
			
			$check = true;
			if( strpos( $email->email, '@mail.ee') ) {
				$check = false;
			}
			
			if( $check && $mail->Send() == true ) {
				$this->sent++;
			} else {
				$this->errors++;
				$v = $this->erroredEmails;
				$v[] = array($email->id,$email->email);
				$this->erroredEmails = $v;
			}
			
			$mail->ClearAddresses();
		}
		
		if( !$this->save() ) {
			throw new RuntimeException('Failed saving NewsletterSend: '.implode(',',DomArValidationReport::getLastReport()->messages));
		}
		
		return true;
	}

}
?>